import base64
import json
import time

from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db.models import Q
from django.http import StreamingHttpResponse, FileResponse
from django.shortcuts import render, HttpResponse
from utils.ResponseResult import success_result_json, fail_result_json
from django.db import connection
from .models import BookInfoModel, FileInfoModel, BookTypeModel
from entity import BookModelConvert
from django.core.files.storage import FileSystemStorage
from django.conf import settings


# Create your views here.

def query_book_list(request):
    json_param = json.loads(request.body.decode("utf-8"))
    bookNo = json_param.get("bookNo", '')
    bookName = json_param.get("bookName", '')
    pageNo = int(json_param.get("pageNo", 1))
    pageSize = int(json_param.get("pageSize", 10))

    # 构建查询条件
    query_params = {}
    if bookNo:
        query_params['book_no'] = bookNo
    if bookName:
        # __icontains 不区分大小写  __contains：区分大小写
        query_params['book_name__contains'] = bookName
    # 查询数据并排序
    books = BookInfoModel.objects.filter(**query_params).order_by('-create_date')
    # 分页
    paginator = Paginator(books, pageSize)
    try:
        books_page = paginator.page(pageNo)
    except PageNotAnInteger:
        # 如果 page 不是整数，取第一页
        books_page = paginator.page(1)
    except EmptyPage:
        # 如果 page 超出范围，取最后一页
        books_page = paginator.page(paginator.num_pages)

    # 将查询结果转换为字典列表
    result = {
        "bookList": BookModelConvert.to_dict_pos(books_page),
        "totals": paginator.count
    }

    return success_result_json(result)


def add_book_info(request):
    try:
        bookNo = request.POST.get("bookNo")
        bookName = request.POST.get("bookName")
        bookAuthor = request.POST.get("bookAuthor")
        bookAvatar = request.FILES.get("bookAvatar", None)
        typeId = request.POST.get("typeId")
        if not bookAvatar:
            return fail_result_json("书籍封面图片不能为空")

        file_name = str(int(time.time())) + "_" + bookAvatar.name
        # 获取文件类型（MIME类型）
        file_type = bookAvatar.content_type
        file_size = bookAvatar.size
        file_url = "http://localhost:30010/static/images/" + file_name

        # 方案一、分块读取上传文件内容并写入目标文件
        # bookAvatarStream = open("./static/images/" + file_name, "wb+")
        # for chunk in bookAvatar.chunks():
        #     bookAvatarStream.write(chunk)
        # bookAvatarStream.close()
        # 方案二、django-file
        fs = FileSystemStorage(location=settings.MEDIA_ROOT)
        fs.save(file_name, bookAvatar)
        file_url = fs.url(file_name)
        # file_url:相对路径   absolute_file_url：绝对路径
        absolute_file_url = request.build_absolute_uri(file_url)

        file_info = FileInfoModel(file_name=file_name, file_url=absolute_file_url, file_type=file_type)
        file_info.save()
        # 保存书籍信息 file_id传入文件对象
        type_info = BookTypeModel(type_id=typeId)
        book_info = BookInfoModel(book_no=bookNo, book_name=bookName, book_author=bookAuthor, file_id=file_info,
                                  type_info=type_info, create_date=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                                  create_user="admin", update_date=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                                  update_user="admin", version=0)
        book_info.save()
        return success_result_json(msg='上传书籍成功')
    except Exception as e:
        return fail_result_json(msg=f"添加书籍异常，{e},请联系管理员", code=500)


def downloadImage(request):
    file_url = request.GET.get("fileUrl")
    download_mode = request.GET.get("downloadMode")
    print(f"入参文件地址：{file_url}, 下载模式：{download_mode}")
    file_name = file_url.split('/')[-1]
    file_path = settings.MEDIA_ROOT + "\\" + file_name
    print(f"文件完整地址：{file_path}")
    new_file_name = str(time.time()) + "_" + file_url.split('/')[-1]
    if download_mode == "blob":
        # 方案一
        # file = open(file_path, 'rb')
        # response = HttpResponse(file)
        # response['Content-Type'] = 'application/octet-stream'
        # response['Content-Disposition'] = 'attachment; filename="%s"' % new_file_name

        # 方案二
        # file = open(file_path, 'rb')
        # response = StreamingHttpResponse(file)
        # response['Content-Type'] = 'application/octet-stream'
        # response['Content-Disposition'] = 'attachment; filename="%s"' % new_file_name

        # 方案三
        file = open(file_path, 'rb')
        response = FileResponse(file)
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment; filename="%s"' % new_file_name
        return response
    elif download_mode == "base64":
        with open(file_path, 'rb') as file:
            file_content = file.read()
        result_data = {
            "imageBase64": base64.b64encode(file_content).decode("utf-8"),
            "fileName": new_file_name
        }
        print(f"result_data: {result_data}")
        return success_result_json(result_data)


def query_book_detail(request):
    books = [
        {
            "id": 111,
            "name": "<<三国>>"
        }
    ]
    return fail_result_json(books)


# http://localhost:8080/testApi?id=121&name=张三
def testApi(request):
    book = BookInfoModel.objects.first()
    book = {
        "id": str(book.id),
        "name": book.book_name,
        # "typeName": book.book_type.type_name
        "fileId": str(book.file_info.file_id),
        "fileName": book.file_info.file_name
    }
    return HttpResponse(f"参数:{book}")


# http://localhost:8080/testApi1/1234
def testApi1(request, user_id):
    cursor = connection.cursor()
    cursor.execute("select * from book_info")
    rows = cursor.fetchall()
    for row in rows:
        print(row[2])
    books = [
        {
            "id": 111,
            "name": "<<三国>>"
        },
        {
            "id": 222,
            "name": "<<水浒>>"
        }
    ]
    return success_result_json(books)
